package demo1;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class TestZk {
    String url="192.168.184.100:2181,192.168.184.101:2181";
    //服务器用来跟客户端发送心跳，如果客户端超过这个时间也没能响应，则服务器认为客户端挂了。
    int timeout=20000;
    ZooKeeper client;

    @Before
    public void init()throws Exception{
        client=new ZooKeeper(url, timeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                List<String>childs;
                System.out.println("============begin==============");
                try{
                    childs=client.getChildren("/", true);
                    for(String c:childs){
                        System.out.println(c);
                    }
                    System.out.println("============end==============");
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }
            }
        });
    }

    @Test
    public void createNode()throws Exception{
        Thread.sleep(3000);
        String path=client.create("/servers","hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("path:"+path);
        Thread.sleep(Integer.MAX_VALUE);
    }

    //删除、修改、查询
    @Test
    public void deleteAndModifyAndRead()throws Exception{
        Stat s=client.exists("/servers",false);
        System.out.println("存在servers 吗？"+(s!=null));

        if(s!=null){
            int version=s.getVersion();
            System.out.println("版本号："+version);
            //client.delete("/servers",0);
            //client.setData("/servers","嘿嘿".getBytes(),version);
            System.out.println(new String(client.getData("/servers",false,null)));
        }
        Thread.sleep(Integer.MAX_VALUE);
    }

}
